package com.youngball.shiro.realm;

import com.youngball.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by asus on 2016/3/28.
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @SuppressWarnings("Duplicates")
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRoles(username));
        Set<String> permissions= userService.findMyPermissions(username);
        Set<String> permissions2=new HashSet<String>();
        for(String permission:permissions){
            String [] aa=  permission.split("@#&&#");
            permissions2.add(aa[1]);
        }
        authorizationInfo.setStringPermissions(permissions2);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
                SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
               "3761ead02e7c50d377f92080ee24b923", //用户名
                "931df6090bacefedcf260ebdc04376b6" ,
                ByteSource.Util.bytes("3761ead02e7c50d377f92080ee24b923"),//salt=username+salt+clubId
                getName()  //realm name
        );

        return authenticationInfo;
    }
}
